<template>
	<div class="main_spac1">
		<div class="main_white padding10">
			<div class="mainor_form">
				<div class="mainor_te">
					<!-- class="mainor_tea" -->
					<el-button @click="Alltongbu">一键同步</el-button>
					<router-link
						:to="{
							name: 'order_batch_record',
							params: { time: form.send_time },
						}"
						><el-button>操作记录</el-button></router-link
					>
				</div>
				<div class="mainsu_te">
					<el-checkbox v-model="synchronous_price"
						>修改后同步至分组报价</el-checkbox
					>
					<el-tooltip class="item" effect="dark" placement="top">
						<div slot="content">
							执行修改后，会同步修改分组报价公式，<br />没有设置公式的修改SKU市场价
						</div>
						<svg aria-hidden="true" class="navbar_svg" width="16" height="16">
							<use xlink:href="#icon-summary_question" />
						</svg>
					</el-tooltip>
				</div>
				<el-form
					:inline="true"
					:model="form"
					class="demo-form-inline"
					ref="userListFrom"
					label-width="70px"
				>
					<el-form-item label="商品名称" prop="goods_spu_id">
						<change-goods-input
							ref="changeGoodsInput"
							@clear="
								() => {
									this.form.goods_spu_id = '';
								}
							"
							@sendValue="
								(data) => {
									this.form.goods_spu_id = data.id;
								}
							"
						></change-goods-input>
					</el-form-item>
					<el-form-item label="商品分类" prop="category_id" class="wid220">
						<el-cascader
							v-model="form.category_id"
							:options="options"
							:props="defaultProps"
						></el-cascader>
					</el-form-item>
					<el-form-item label="配送时间" prop="send_time">
						<el-date-picker
							v-model="form.send_time"
							type="date"
							class="time220"
							:editable="false"
							placeholder="配送时间"
							value-format="yyyy-MM-dd"
							:clearable="false"
						/>
					</el-form-item>
					<el-form-item>
						<el-button class="reset marginLeft10" type="primary" @click="reset"
							>重置</el-button
						>
						<el-button
							type="primary"
							@click="getArticleList"
							:loading="listLoading"
							>搜索</el-button
						>
					</el-form-item>
				</el-form>
			</div>
			<div class="main_table row-expand-down" style="min-height: 670px">
				<el-table
					ref="multipleTable"
					v-loading="listLoading"
					:data="data_list"
					element-loading-text="加载中"
					fit
					border
					highlight-current-row
					:row-class-name="getRowClass"
				>
					<el-table-column type="expand" width="1">
						<template slot-scope="props">
							<div class="maincg_ul">
								<ul class="boxha">
									<li
										class="box"
										v-for="(item, index) in props.row.group"
										:key="index"
									>
										<span>{{ item.title }}：</span>
										<div class="maincg_uli">
											<el-input
												v-model.trim="item.real_price"
												class="wid110"
												:ref="'maincg' + String(props.$index) + String(index)"
												@blur.prevent="
													(val) => {
														maincgBlur(val, props.$index, index);
													}
												"
												@keyup.enter.native="$event.target.blur"
											></el-input>
										</div>
									</li>
								</ul>
							</div>
						</template>
					</el-table-column>

					<el-table-column
						label="商品名称"
						prop="goods_name"
						class-name="main_hei"
					>
						<template slot-scope="scope">
							{{ scope.row.goods.name }}【{{
								scope.row.spu_name ? scope.row.spu_name.title : ""
							}}】
						</template>
					</el-table-column>
					<el-table-column
						label="商品规格"
						prop="spu_unit.title"
						class-name="main_hei"
					/>
					<el-table-column
						label="采购价"
						prop="purchase_price"
						class-name="main_hei"
						><template slot-scope="scope">
							<span :style="{ color: scope.row.red ? 'red' : '' }">{{
								scope.row.purchase_price
							}}</span>
						</template>
					</el-table-column>
					<el-table-column
						label="今日报价"
						prop="market_price"
						class-name="main_hei"
						width="400"
					>
						<template slot-scope="scope">
							<div class="boxha maincg_bj">
								<p>
									<span>未分组：</span>
									{{ scope.row.market_price ? scope.row.market_price : "" }}
								</p>
								<p v-for="(item, index) in scope.row.group" :key="index">
									<span>{{ item.title }}：</span>{{ item.real_price }}
									{{ item.category_price > 0 ? "（分类）" : "" }}
								</p>
							</div>
						</template>
					</el-table-column>
					<el-table-column
						label
						prop="userNickname"
						class-name="main_hei"
						width="200"
						align="center"
					>
						<template slot-scope="scope">
							<el-link
								type="green"
								v-if="scope.row.down"
								@click="formula_save(scope.row, scope.$index)"
								>保存</el-link
							>
							<el-link
								type="primary"
								@click="formula_tongbu(scope.row, scope.$index)"
								>同步</el-link
							>
							<el-link
								type="danger"
								class="maincg_xa"
								@click="formula_meth(scope.row, scope.$index)"
								v-if="!scope.row.down"
								>修改</el-link
							>
							<el-link
								type="success"
								class="maincg_xa"
								@click="formula_meth(scope.row, scope.$index)"
								v-if="scope.row.down"
								>收起</el-link
							>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="main_page boxdq">
				<div></div>

				<!-- <div class="main_page_r">
          <el-pagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div> -->
			</div>
		</div>
		<!-- 批量同步 -->
		<el-dialog
			:title="'已选择' + data_list.length + '个商品，同步中！'"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			@close="close"
			:visible.sync="addedFormVisible"
			class="main_dialog dialog450"
		>
			<div class="notice">
				<el-progress
					:text-inside="true"
					:stroke-width="15"
					:percentage="percent"
					status="success"
					color="#19B098"
				></el-progress>
				<div class="progress_list">
					<template v-for="(percent_list, index) in reverseSum">
						<template v-if="index < 5">
							<p v-if="percent_list.type == 1" :key="index">
								商品id:{{ percent_list.order_id }}，同步已成功
							</p>
							<p v-else class="progress_list_red" :key="index">
								商品id:{{ percent_list.order_id }}，同步失败
							</p>
						</template>
					</template>
					<p v-if="percent == 100" class="progress_list_su">
						同步已经完成请关闭弹框!
					</p>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { mapGetters } from "vuex";
	import {
		orderList_pricing,
		order_savePrice,
		orderList_batchDispatchPricing,
		hasUnrecordedGoods, //单个商品同步或保存
		hasUnrecordedOrder, //批量同步
	} from "@/api/order/orderBatch";
	import { apiUrl, objKeySort, Md5 } from "@/utils/public";
	import { parseTime, recursion, category } from "@/utils/index";

	import ChangeGoodsInput from "@/components/ChangeGoodsInput";
	import { group_index } from "@/api/user/userGroup";

	export default {
		directives: {
			// 聚焦元素
			focus: {
				inserted(el) {
					el.querySelector("input").focus();
				},
			},
		},
		computed: {
			...mapGetters(["avatar"]),
			reverseSum() {
				return this.percent_list.reverse();
			},
		},
		data() {
			return {
				// 分页
				current: {
					page: 1,
					per_page: 20,
				},
				limit: 20,
				totalCount: 1,
				// 搜索
				// 搜索
				form: {
					pid: "",
					category_id: [],
					send_time: parseTime(new Date(), "{y}-{m}-{d}"),
					goods_spu_id: "",
					is_standard: null,
					current_price: null,
				},
				// 分类
				options: [],
				defaultProps: {
					children: "selfNext",
					label: "title",
					value: "id",
					checkStrictly: true,
				},
				offsetParent: true,
				synchronous_price: true,
				// 更多
				moredata: false,
				data_list: [],
				listLoading: false,
				selectArr: [],
				// 批量同步
				percent_gs: 0,
				percent: 0,
				percent_list: [],
				addedFormVisible: false,
			};
		},
		created() {
			// 列表
			this.orderList_pricing();
		},
		mounted() {
			window.Echo.channel(
				"batchDispatchPricing." + this.avatar.company_id
			).listen("BatchDispatchPricingEvent", (e) => {
				this.percent_gs = parseInt(this.percent_gs) + 1;
				if ((this.percent_gs / this.selectArr.length) * 100 >= 100) {
					this.percent = 100;
					return;
				}
				this.percent =
					this.percent_gs / this.selectArr.length
						? parseInt((this.percent_gs / this.selectArr.length) * 100)
						: 0;
				if (e.notice.msg == "ok") {
					this.percent_list.push({
						num: this.percent,
						type: 1,
						order_id: e.notice.goods_spu_id,
					});
				} else {
					this.percent_list.push({
						num: this.percent,
						type: 2,
						order_id: e.notice.goods_spu_id,
					});
				}
			});
		},
		methods: {
			close() {
				this.percent = 0;
				this.percent_gs = 0;
				this.percent_list = [];
				this.orderList_pricing();
				// this.$refs["userListFrom1"].clearValidate();
			},
			handleCeshi() {
				this.$myConfirm("此操作将永久删除该文件, 是否继续?", "测试", {
					confirmButtonText: "确认",
					cancelButtonText: "取消",
					threesButtonText: "确认并回单",
					type: "warning",
				})
					.then((val) => {
						console.log(val);
						this.$message({
							type: "success",
							message: "删除成功!",
						});
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除",
						});
					});
			},
			// 一键同步
			Alltongbu() {
				let ids = [];
				this.data_list.map((item) => {
					ids.push(item.id);
				});
				let form = {
					ids: JSON.stringify(ids),
					send_time: this.form.send_time,
					synchronous_price: this.synchronous_price ? 1 : 0,
				};
				if (ids.length != 0) {
					this.$confirm("确定一键同步所有商品的最新报价?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "info",
					})
						.then(() => {
							this.hasUnrecordedOrder().then((res) => {
								if (res.errcode == 0) {
									this.setupmine(form);
								} else {
									let message = `${res.errmsg},确定继续一键同步吗?`;
									this.$confirm(message, "提示", {
										confirmButtonText: "确定",
										cancelButtonText: "取消",
										type: "warning",
									})
										.then(() => {
											this.setupmine(form);
										})
										.catch(() => {});
								}
							});
						})
						.catch(() => {});
				} else {
					this.$message.error("暂无可批量同步的商品");
				}
			},
			// 批量同步前查询
			hasUnrecordedOrder() {
				let form = {
					send_time: this.form.send_time,
				};
				return new Promise((resolve, reject) => {
					hasUnrecordedOrder(form).then((res) => {
						resolve(res);
					});
				});
			},
			// 确认一键同步
			setupmine(form) {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					form
				);
				orderList_batchDispatchPricing(data).then((res) => {
					this.addedFormVisible = true;
				});
			},
			// 判断表格是否有子项，无子项不显示展开按钮
			getRowClass(row) {
				if (row.row.child) {
					if (row.row.child.length === 0) {
						return "maincg_cover";
					}
				}
			},
			// 报价公式-展开行
			formula_meth(row, index) {
				let $table = this.$refs.multipleTable;
				this.data_list[index].down = !this.data_list[index].down;
				this.data_list.map((item) => {
					if (item.down) {
						$table.toggleRowExpansion(item, true);
					} else {
						$table.toggleRowExpansion(item, false);
					}
				});
			},
			// 同步按钮
			formula_tongbu(row, index) {
				let groupArr = [];
				for (let i in row.group) {
					let obj = {
						id: row.group[i].group_id,
						price: row.group[i].real_price,
					};
					groupArr.push(obj);
				}
				let name = `${row.goods.name}【${row.spu_name.title}】`;

				this.$confirm(`确定同步 "${name}" 的最新报价？`, "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "info",
				})
					.then(() => {
						let form = {
							id: row.id,
							price: JSON.stringify(groupArr),
							send_time: this.form.send_time,
							synchronous_price: this.synchronous_price ? 1 : 0,
						};
						this.hasUnrecordedGoods(row).then((res) => {
							if (res.errcode == 0) {
								this.confirmTongbu(form);
							} else {
								let message = `"${name}"${res.errmsg},确定继续同步吗?`;
								this.$confirm(message, "提示", {
									confirmButtonText: "确定",
									cancelButtonText: "取消",
									type: "warning",
								})
									.then(() => {
										this.confirmTongbu(form);
									})
									.catch(() => {});
							}
						});
					})
					.catch(() => {});
			},
			// 确认同步
			confirmTongbu(form) {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					form
				);
				order_savePrice(data).then((res) => {
					if (res.errcode == 0) {
						this.$message.success("同步成功");
						this.orderList_pricing();
					} else {
						this.$message.error(res.errmsg);
					}
				});
			},
			// 同步保存前查询状态
			hasUnrecordedGoods(row) {
				let form = {
					send_time: this.form.send_time,
					goods_spu_id: row.id,
				};
				return new Promise((resolve, reject) => {
					hasUnrecordedGoods(form).then((res) => {
						resolve(res);
					});
				});
			},
			// 保存
			formula_save(row, index) {
				let groupArr = [];
				for (let i in row.group) {
					if (row.group[i].isChange) {
						let obj = {
							id: row.group[i].group_id,
							price: row.group[i].real_price,
						};
						groupArr.push(obj);
					}
				}
				let name = `${row.goods.name}【${row.spu_name.title}】`;
				this.$confirm(`确定修改 "${name}" 的配送单价？`, "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "info",
				})
					.then(() => {
						let form = {
							id: row.id,
							price: JSON.stringify(groupArr),
							send_time: this.form.send_time,
							synchronous_price: this.synchronous_price ? 1 : 0,
						};
						this.hasUnrecordedGoods(row).then((res) => {
							if (res.errcode == 0) {
								this.confirmSave(form);
							} else {
								let message = `"${name}"${res.errmsg},确定继续修改吗?`;
								this.$confirm(message, "提示", {
									confirmButtonText: "确定",
									cancelButtonText: "取消",
									type: "warning",
								})
									.then(() => {
										this.confirmSave(form);
									})
									.catch(() => {});
							}
						});
					})
					.catch(() => {});
			},
			// 确认保存
			confirmSave(form) {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					form
				);
				order_savePrice(data).then((res) => {
					if (res.errcode == 0) {
						this.$message.success("修改成功");
						this.formula_meth(row, index);
						this.orderList_pricing();
					} else {
						this.$message.error(res.errmsg);
					}
				});
			},
			// 分类
			handleChange(value) {
				console.log(value);
			},
			// 点击报价
			offer(index, index1) {
				this.data_list[index].group[index1].disabled =
					!this.data_list[index].group[index1].disabled;
				this.$nextTick(() => {
					this.$refs[
						"maincg" + String(index) + String(index1)
					][0].$el.offsetParent
						.querySelector("input")
						.focus();
				});
			},
			// 报价焦点离开
			maincgBlur(val, index, index1) {
				if (
					/^(\d+\.?)?\d{0,2}$/.test(val.target.value) &&
					val.target.value != ""
				) {
					this.data_list[index].group[index1].disabled = true;
					this.data_list[index].group[index1].isChange = true;
				} else {
					this.$nextTick(() => {
						if (val.target.offsetParent) {
							val.target.offsetParent.querySelector("input").focus();
						}
						this.$message.error("请输入数字");
						val.target.value = 0.0;
					});
				}
			},
			// 搜索
			getArticleList() {
				this.current.page = 1;
				this.orderList_pricing();
			},
			reset() {
				this.$refs["userListFrom"].resetFields();
				this.$refs["changeGoodsInput"].name = "";
				this.getArticleList();
			},
			// 更多
			more() {
				this.moredata = !this.moredata;
			},
			// 分页
			changeLimit(pageSize) {
				this.pageSize = pageSize;
			},
			changePage(page) {
				this.page = page;
			},
			// 列表
			orderList_pricing() {
				this.listLoading = true;
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(
								Object.assign(apiUrl().name, this.list_form(), this.current)
							) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					this.list_form(),
					this.current
				);
				orderList_pricing(data).then((res) => {
					this.listLoading = false;
					if (res.errcode == 0) {
						this.options = recursion(res.data.categoryList, true);
						res.data.list.map((e) => {
							e.show = false;
							e.red = false;
							if (parseFloat(e.market_price) < parseFloat(e.purchase_price)) {
								e.red = true;
							}
							for (let key in e.group) {
								e.group[key].disabled = true;
								e.group[key].isChange = false;
							}
						});
						this.data_list = res.data.list;
					} else {
						this.$message.error(res.errmsg);
					}
				});
			},

			list_form() {
				let form = JSON.parse(JSON.stringify(this.form));
				form.pid = form.category_id[0] ? form.category_id[0] : "";
				form.category_id = category(form.category_id);
				return form;
			},
		},
	};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.mainor_form {
	min-height: 70px;
}
.maincg_ul {
	ul {
		padding-left: 80px;
		li {
			margin-left: 40px;
			margin-right: 40px;
			margin-top: 6px;
			margin-bottom: 6px;
			align-items: center;
			span {
				font-size: $font_14;
				color: $colour_3;
			}
			/deep/.el-select {
				margin-left: 5px;
			}
			.maincg_uli {
				margin-left: 5px;
				position: relative;
				.maincg_uli_s {
					position: absolute;
					right: 10px;
					top: 8px;
					z-index: 9;
					use {
						fill: $menuText;
					}
					&:hover {
						cursor: pointer;
						use {
							fill: $menuActiveText;
						}
					}
				}
			}
		}
	}
}
.maincg_bj {
	margin-left: -30px;
	p {
		span {
			display: inline-block;
			min-width: 56px;
			text-align: right;
		}
		margin-left: 30px;
		color: $menuText;
		font-size: $font_14;
	}
}
.mainus_pe {
	svg {
		vertical-align: -3px;
		margin-left: 30px;
	}
	use {
		fill: $menuText;
	}
	&:hover {
		cursor: pointer;
		use {
			fill: $menuActiveText;
		}
	}
}
.notice {
	.progress_list {
		padding: 15px 0;
	}
}
</style>
